<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    @close="closeDialog(false)"
  >
    <el-form
      ref="addOrEditFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="100"
      size=""
      :disabled="dialogAddOrEdit.detail === '详情'"
    >
      <el-row justify="start" class="">
        <el-col :span="itemSpan" class="">
          <el-form-item label="项目名称" prop="projectId">
            <el-input v-model="formData.projectName" disabled placeholder="请选择" />
            <el-button type="primary" plain style="position: absolute; right: 0px" @click="handleSelectProject"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="参建单位" prop="corpId">
            <el-select v-model="formData.corpId" class="last-select" placeholder="请选择" clearable>
              <el-option v-for="item in projectCorps" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan" class="">
          <el-form-item label="设备分类" prop="type">
            <el-select v-model="formData.type" placeholder="请选择设备分类" filterable clearable>
              <el-option
                v-for="item in ProjectCheckInDeviceType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="itemSpan" class="">
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入设备名称" />
          </el-form-item>
        </el-col>

        <el-col :span="itemSpan" class="">
          <el-form-item label="设备序列号" prop="code">
            <el-input v-model="formData.code" placeholder="请输入设备序列号" />
          </el-form-item>
        </el-col>

        <el-col :span="itemSpan" class="">
          <el-form-item label="进/出口" prop="inOut">
            <el-select v-model="formData.inOut" placeholder="请选择进/出口" filterable clearable>
              <el-option label="进口" :value="inOut_in"></el-option>
              <el-option label="出口" :value="inOut_out"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="itemSpan" class="">
          <el-form-item label="有效起始日期" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
            />
          </el-form-item>
        </el-col>

        <el-col :span="itemSpan" class="">
          <el-form-item label="有效截至日期" prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              :disabled="!formData.startDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
            />
          </el-form-item>
        </el-col>

        <el-col :span="itemSpan" class="">
          <el-form-item label="设备型号" prop="model">
            <el-input v-model="formData.model" placeholder="请输入设备型号" />
          </el-form-item>
        </el-col>

        <el-col :span="itemSpan" class="">
          <el-form-item label="设备版本" prop="version">
            <el-input v-model="formData.version" placeholder="请输入设备版本" />
          </el-form-item>
        </el-col>

        <el-col :span="21" class="">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" :row="3" style="width: 100%" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
      <select-project :dialog-select="dialogSelectProject" @select-send-close="projectSendClose"></select-project>
    </el-form>

    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddOrEdit.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<!-- 新增/修改弹框 -->
<script lang="ts" setup>
import { ref, reactive, computed } from "vue";
import { addCheckInDevice, editCheckInDevice, getCheckInDeviceInfo } from "@/api/system/device/index";
import { getProjectCorps } from "@/api/common/corp";
import { ProjectCheckInDeviceForm } from "@/api/system/device/types";
import SelectProject from "@/views/common/SelectProject/index.vue";
import { getDicts } from "@/store/modules/dict";
import type { FormRules } from "element-plus";

import { useScreen } from "@/store/modules/screen";

const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(900);
const itemSpan = ref(12);
const formData = reactive<ProjectCheckInDeviceForm>({});

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 900;
    itemSpan.value = 12;
  }
}

const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增考勤设备信息",
      footBtn: "新增",
      projectId: 0,
    }),
  },
});

const dialogSelectProject = reactive({
  visible: false,
  title: "选择项目",
  footBtn: "确认",
  id: 0,
  type: "allproject",
});
const projectCorps = ref<any[]>([]);

const handleSelectProject = function () {
  dialogSelectProject.visible = true;
};

const projectSendClose = function (info: any) {
  dialogSelectProject.visible = false;
  if (info) {
    formData.projectName = info.name;
    formData.projectId = info.projectId;
    formData.corpId = undefined;
    loadProjectCorps();
  }
};

const loadProjectCorps = () => {
  if (!formData.projectId) {
    return;
  }
  if (formData.projectId) {
    getProjectCorps(formData.projectId).then((res) => {
      if (res.type == 0) {
        if (res.success) {
          projectCorps.value = res.data;
        } else {
        }
      } else {
      }
    });
  }
  return;
};

const emit = defineEmits(["sendClose"]);

const loading = ref(false);
const inOut_in = ref(1);
const inOut_out = ref(2);
let visible = ref(props.dialogAddOrEdit.visible);

const addOrEditFormRef = ref(ElForm);

const rules = reactive<FormRules<ProjectCheckInDeviceForm>>({
  type: [{ required: true, message: "请选择设备分类", trigger: "blur" }],
  name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入设备序列号", trigger: "blur" }],
  startDate: [{ required: true, message: "请选择有效起始日期", trigger: "blur" }],
  endDate: [
    { required: true, message: "请选择有效截至日期", trigger: "blur" },
    { required: true, trigger: "blur", validator: endDataBlur },
  ],
  inOut: [{ required: true, message: "请选择设备进出口", trigger: "blur" }],
  projectId: [{ required: true, message: "请选择项目", trigger: "blur" }],
  corpId: [{ required: true, message: "请选择所属公司", trigger: "blur" }],
});

onMounted(async () => {
  initScreen();

  let tempFormData;
  if (props.dialogAddOrEdit.id) {
    loading.value = true;
    tempFormData = await getCheckInDeviceInfo(props.dialogAddOrEdit.id);
    tempFormData = tempFormData.data;
    Object.assign(formData, tempFormData);
    loadProjectCorps();
    loading.value = false;
    tempFormData = null;
  }
});

function endDataBlur(rule: any, value: any, callback: any) {
  if (new Date(formData.startDate ?? "") > new Date(value)) {
    callback(new Error("截至日期不能小于起始日期!"));
    return;
  } else {
    callback();
  }
}

/* 发送当前弹窗关闭 */
function sendClose(query: boolean) {
  emit("sendClose", query);
}

/**
 * 关闭弹窗
 */
function closeDialog(query: boolean) {
  visible.value = false;
  sendClose(query);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();

  formData.id = undefined;
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        editCheckInDevice(id, formData)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              closeDialog(true);
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (loading.value = false));
      } else {
        addCheckInDevice(formData)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              closeDialog(true);
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
const ProjectCheckInDeviceType = getDicts("projectCheckInDeviceType"); //设备分类
</script>

<style scoped></style>

<style lang="scss" scoped>
.d_left {
  margin-left: 0px;
}
:deep(.el-form-item) {
  flex-wrap: wrap;
}
.dialog_footer {
  // display: flex;
  // justify-content: center;
}

:deep(.el-input) {
  width: 80%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
</style>
